package app.itgungnir.compose.wan.utils

import com.google.gson.Gson
import com.google.gson.JsonElement
import com.google.gson.JsonObject
import com.google.gson.reflect.TypeToken

val jsonParser by lazy { Gson() }

inline fun <reified T> JsonElement.convert(): T? = try {
    jsonParser.fromJson(this, object : TypeToken<T>() {}.type)
} catch (e: Exception) {
    e.printStackTrace()
    null
}

suspend inline fun <reified T> JsonObject.wanResponse(): T? = when (this.get("errorCode")?.asInt) {
    null -> throw IllegalArgumentException("响应结构错误！")
    0 -> this.get("data")?.convert<T>()
    -1001 -> {
        LocalDataStore.updateLocalData {
            it.clearHasLogin()
            it.clearWanAndroidCookies()
            it.clearUserInfo()
            it.clearCoinInfo()
        }
        WanDatabase.instance.onUserLogout()
        throw IllegalStateException(this.get("errorMsg")?.asString ?: "登录态失效，请重新登录！")
    }
    else -> throw IllegalArgumentException(this.get("errorMsg")?.asString ?: "未知错误！")
}
